package com.zsk.shop.api.order;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.zsk.shop.model.results.LogisticsNameResult;
import com.zsk.shop.model.results.LogisticsResult;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Ys
 * @date 2021年10月25日 17:17
 */
@Slf4j
public class OrderStatus {

    private static String HOST = "https://wuliu.market.alicloudapi.com";
    private static String APP_CODE = "32a2e73f8e1142fa813735955f31cfd4";

    public static void main(String[] args) {
      log.info(getOrderInfo("JT5078664338601"));
    }

    /**
     * 获取物流状态
     * @param number
     * @return
     */
    public static String getOrderInfo(String number){
        String path = "/kdi";
        String type = "";
        String urlSend = HOST + path + "?no=" + number +"&type="+type;
        try {
            URL url = new URL(urlSend);
            HttpURLConnection httpURLCon = (HttpURLConnection) url.openConnection();
            httpURLCon.setRequestProperty("Authorization", "APPCODE " + APP_CODE);
            int httpCode = httpURLCon.getResponseCode();
            if (httpCode == 200) {
                String json = read(httpURLCon.getInputStream());
                log.info("返回值："+json);
                return json;
            } else {
                Map<String, List<String>> map = httpURLCon.getHeaderFields();
                String error = map.get("X-Ca-Error-Message").get(0);
                if (httpCode == 400 && error.equals("Invalid AppCode `not exists`")) {
                    log.info("AppCode错误 ");
                } else if (httpCode == 400 && error.equals("Invalid Url")) {
                    log.info("请求的 Method、Path 或者环境错误 ");
                } else if (httpCode == 400 && error.equals("Invalid Param Location")) {
                    log.info("参数错误 ");
                } else if (httpCode == 403 && error.equals("Unauthorized")) {
                    log.info("服务未被授权（或URL和Path不正确 ");
                } else if (httpCode == 403 && error.equals("Quota Exhausted")) {
                    log.info("套餐包次数用完 ");
                } else {
                    log.info("参数名错误 或 其他错误 ");
                    log.info("异常信息 "+error);
                }
                return error;
            }
        } catch (Exception e) {
             e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取物流状态，物流名称
     *  0：快递收件(揽件)1.在途中 2.正在派件 3.已签收 4.派送失败 5.疑难件 6.退件签收
     * @param number
     * @return
     */
    public static Map<String, String> getLogisticsName(String number){
        String path = "/kdi";
        String type = "";
        String urlSend = HOST + path + "?no=" + number +"&type="+type;
        try {
            URL url = new URL(urlSend);
            HttpURLConnection httpURLCon = (HttpURLConnection) url.openConnection();
            httpURLCon.setRequestProperty("Authorization", "APPCODE " + APP_CODE);
            int httpCode = httpURLCon.getResponseCode();
            if (httpCode == 200) {
                String json = read(httpURLCon.getInputStream());
                log.info("返回值："+json);
                JSONObject jsonObject = JSONObject.parseObject(json);
                String status = jsonObject.getString("status");
                if(status.equals("0")){
                    Map<String, String> map = new HashMap<>(2);
                    String result = jsonObject.getString("result");
                    JSONObject jsonObject1 = JSONObject.parseObject(result);
                    map.put("deliveryStatus", jsonObject1.getString("deliverystatus"));
                    map.put("expName", jsonObject1.getString("expName"));
                    return map;
                }
                return null;
            } else {
                Map<String, List<String>> map = httpURLCon.getHeaderFields();
                String error = map.get("X-Ca-Error-Message").get(0);
                if (httpCode == 400 && error.equals("Invalid AppCode `not exists`")) {
                    log.info("AppCode错误 ");
                } else if (httpCode == 400 && error.equals("Invalid Url")) {
                    log.info("请求的 Method、Path 或者环境错误 ");
                } else if (httpCode == 400 && error.equals("Invalid Param Location")) {
                    log.info("参数错误 ");
                } else if (httpCode == 403 && error.equals("Unauthorized")) {
                    log.info("服务未被授权（或URL和Path不正确 ");
                } else if (httpCode == 403 && error.equals("Quota Exhausted")) {
                    log.info("套餐包次数用完 ");
                } else {
                    log.info("参数名错误 或 其他错误 ");
                    log.info("异常信息 "+error);
                }
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 根据订单号获取物流公司名称
     * @param number
     */
    public static String getName(String number) {
        String name = "未知";
        // 【2】后缀
        String path = "/exCompany";
        // 【5】拼接请求链接
        String urlSend = HOST + path + "?no=" + number;
        try {
            URL url = new URL(urlSend);
            HttpURLConnection httpURLCon = (HttpURLConnection) url.openConnection();
            httpURLCon.setRequestProperty("Authorization", "APPCODE " + APP_CODE);
            int httpCode = httpURLCon.getResponseCode();
            if (httpCode == 200) {
                String json = read(httpURLCon.getInputStream());
                log.info("返回值 "+json);
                LogisticsResult result = new Gson().fromJson(json, LogisticsResult.class);
                if(result.getList().size() > 0){
                    LogisticsNameResult obj = result.getList().get(0);
                    return obj.getName();
                }
                return name;
            } else {
                Map<String, List<String>> map = httpURLCon.getHeaderFields();
                String error = map.get("X-Ca-Error-Message").get(0);
                if (httpCode == 400 && error.equals("Invalid AppCode `not exists`")) {
                    log.info("AppCode错误 ");
                } else if (httpCode == 400 && error.equals("Invalid Url")) {
                    log.info("请求的 Method、Path 或者环境错误 ");
                } else if (httpCode == 400 && error.equals("Invalid Param Location")) {
                    log.info("参数错误 ");
                } else if (httpCode == 403 && error.equals("Unauthorized")) {
                    log.info("服务未被授权（或URL和Path不正确 ");
                } else if (httpCode == 403 && error.equals("Quota Exhausted")) {
                    log.info("套餐包次数用完 ");
                } else {
                    log.info("参数名错误 或 其他错误 ");
                    log.info("异常信息 "+error);
                }
            }
        } catch (Exception e) {
             e.printStackTrace();
        }
        return name;
    }

    // 读取返回结果
    private static String read(InputStream is) throws IOException {
        StringBuffer sb = new StringBuffer();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line = null;
        while ((line = br.readLine()) != null) {
            line = new String(line.getBytes(), "utf-8");
            sb.append(line);
        }
        br.close();
        return sb.toString();
    }

}
